package com.guli.gulimall.product.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.gulimall.product.entity.CategoryEntity;
import com.guli.gulimall.product.service.CategoryService;
import com.guli.gulimall.product.vo.Category1Vo;
import com.guli.gulimall.product.vo.Category2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 6y
 * @ClassName IndexController.java
 * @Description TODO
 * @createTime 2022-04-08 15:54:00
 */
@Controller
public class IndexController {

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private RedisTemplate redisTemplate;

	@RequestMapping(value = {"/","index"})
	public String index(Model model){
		QueryWrapper<CategoryEntity> w = new QueryWrapper<>();
		w.eq("parent_cid",0);
		//一级列表
		List<CategoryEntity> list = categoryService.list(w);
		model.addAttribute("list",list);
		return "index";
	}
	@RequestMapping("catalog")
	@ResponseBody
	public Map<Long, List<Category1Vo>> catalog(){
		Map<Long, List<Category1Vo>> map = (Map<Long, List<Category1Vo>>) redisTemplate.boundHashOps("map").get("categoryTreeList");
		if (map!=null) {
			System.out.println("从redis中获取");
			//redis中有
			return map;
		}
		System.out.println("redis中不存在，从mysql拿");
		//先访问一遍数据库，拿到所有数据
		List<CategoryEntity> allList = categoryService.list(null);
		//以流的方式过滤
		map = allList.stream().filter(item -> {
			//过滤出第一级列表
			return item.getParentCid().equals(0L);
			//将流组合成map
		}).collect(Collectors.toMap(k -> {
			return k.getCatId();
		}, v -> {
			List<CategoryEntity> l2List = findChildren(allList, v);
			return l2List.stream().map(l2 -> {
				Category1Vo category1Vo = new Category1Vo();
				category1Vo.setCatalog1Id(v.getCatId());
				category1Vo.setId(l2.getCatId());
				category1Vo.setName(l2.getName());
				List<CategoryEntity> l3List = findChildren(allList, l2);
				category1Vo.setCatalog3List(l3List.stream().map(l3->{
					Category2Vo category2Vo = new Category2Vo();
					category2Vo.setCatalog2Id(l2.getCatId());
					category2Vo.setId(l3.getCatId());
					category2Vo.setName(l3.getName());
					return category2Vo;
				}).collect(Collectors.toList()));
				return category1Vo;
			}).collect(Collectors.toList());
		}));
		redisTemplate.boundHashOps("map").put("categoryTreeList",map);
		//获取到树形列表
		return map;
	}

	private List<CategoryEntity> findChildren(List<CategoryEntity> allList, CategoryEntity category) {
		List<CategoryEntity> list =  allList.stream().filter(item -> {
			//过滤出子列表
			return item.getParentCid().equals(category.getCatId());
		}).collect(Collectors.toList());
		//返回子列表
		return list;
	}
}
